﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Web.Services;
using System.Web.Mvc;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security.Roles;
using DotNetNuke.Modules.ActiveSocialMigrator.Data;
using Active.Modules.Social;
using DotNetNuke.Security.Roles.Internal;
using DotNetNuke.Services.FileSystem;
using System.IO;
using System.Data;
using DotNetNuke.Services.Journal;
using DotNetNuke.Modules.ActiveSocialMigrator.Utilities;

namespace DotNetNuke.Modules.ActiveSocialMigrator.Services
{
    [DnnAuthorize]
    public class GroupServiceController : DnnController
    {
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult ConvertGroup(int GroupId, int RoleGroupId)
        {
            RoleController roleController = new RoleController();
            var groupsDB = new GroupsDB();
            GroupInfo group = groupsDB.Group_Get(GroupId, PortalSettings.PortalId);
            RoleInfo roleInfo = new RoleInfo()
            {
                PortalID = PortalSettings.PortalId,
                RoleName = group.GroupName,
                Description = group.GroupDescription,
                SecurityMode = SecurityMode.SocialGroup,
                Status = RoleStatus.Approved

            };
            bool reviewMembers = false;
            if (group.AccessType == GroupAccessTypes.GroupOpen)
            {
                roleInfo.IsPublic = true;
            } else if (group.AccessType == GroupAccessTypes.GroupClosed)
            {
                roleInfo.IsPublic = true;
                reviewMembers = true;
            } else
            {
                roleInfo.IsPublic = false;
            }
            roleInfo.RoleGroupID = RoleGroupId;

            roleInfo.RoleID = roleController.AddRole(roleInfo);
            groupsDB.CreateGroupMap(group.GroupId, roleInfo.RoleID);
            roleInfo.Settings.Add("GroupCreatorName", group.GroupOwner.DisplayName);
            roleInfo.Settings.Add("ReviewMembers", reviewMembers.ToString());
            roleInfo.Settings.Add("City", group.City);
            roleInfo.Settings.Add("Country", group.Country);
            roleInfo.Settings.Add("Region", group.Region);
            roleInfo.Settings.Add("Street", group.Street);
            roleInfo.Settings.Add("WebSite", group.WebSiteURL);

            TestableRoleController.Instance.UpdateRoleSettings(roleInfo, true);
            IFileManager _fileManager = FileManager.Instance;
            IFolderManager _folderManager = FolderManager.Instance;
            var rootFolderPath = PathUtils.Instance.FormatFolderPath(PortalSettings.HomeDirectory);
            try
            {
                if (!String.IsNullOrEmpty(group.GroupIcon))
                {
                    String asGroupIconPath = PathUtils.Instance.MapPath(String.Format("~/Portals/{0}/activesocial/groups/_icons/gp_{1}.png", PortalSettings.PortalId, group.GroupId));
                    if (System.IO.File.Exists(asGroupIconPath))
                    {

                        IFolderInfo groupFolder = _folderManager.GetFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID);
                        if (groupFolder == null)
                        {
                            groupFolder = _folderManager.AddFolder(PortalSettings.PortalId, "Groups/" + roleInfo.RoleID);
                        }
                        if (groupFolder != null)
                        {
                            var fileName = Path.GetFileName(asGroupIconPath);
                            var file = System.IO.File.Open(asGroupIconPath, FileMode.Open);
                            var fileInfo = _fileManager.AddFile(groupFolder, fileName, file);
                            roleInfo.IconFile = "FileID=" + fileInfo.FileId;
                            roleController.UpdateRole(roleInfo);
                            file.Close();
                        }
                    }

                }
            }
            catch
            {
            }
            

            roleController.AddUserRole(PortalSettings.PortalId, group.GroupOwner.UserID, roleInfo.RoleID, RoleStatus.Approved, true, Null.NullDate, Null.NullDate);
            //Migrate Members
            DataTable members = groupsDB.Groups_Members_List(group.GroupId, PortalSettings.PortalId, 1, 0, int.MaxValue, false);
            foreach (DataRow dr in members.Rows)
            {
                try
                {

                    roleController.AddUserRole(PortalSettings.PortalId, Convert.ToInt32(dr["UserId"].ToString()), roleInfo.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate);
                }
                catch
                {
                }
            }
          
            return Json(new { Result = "success" });
        }
        
    }
}